package tech.daoxuan.security.core.validate.code;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import tech.daoxuan.security.core.validate.code.sms.SmsCodeSender;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName ValidateCodeController
 * @Description TODO
 * @Author 10983
 * @Date 2019/6/21 20:53
 * @Version 1.0
 */
@RestController
public class ValidateCodeController {

    public static  final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";


    @Autowired
    private ValidateCodeGenerator imageCodeGenerator;
    @Autowired
    private ValidateCodeGenerator smsCodeGenerator;


    @Autowired
    private SmsCodeSender smsCodeSender;


    //操作session的工具类
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @GetMapping("/code/image")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode= (ImageCode) imageCodeGenerator.generate(new ServletWebRequest(request));
        //sessionStrategy会从 request中取session
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode);

        //写到页面  ImageIO是图片IO流 工具
        ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());

    }
    @GetMapping("/code/sms")
    public void createSmsCode(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletRequestBindingException {
        ValidateCode smsCode= smsCodeGenerator.generate(new ServletWebRequest(request));
        //sessionStrategy会从 request中取session
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,smsCode);
        String mobile = ServletRequestUtils.getRequiredStringParameter(request, "mobile");
        //写到页面  ImageIO是图片IO流 工具
        smsCodeSender.send(mobile, smsCode.getCode());
    }
}
